# login/views.py
from django.core.paginator import Paginator
from django.shortcuts import render,redirect
from . import models
from .forms import UserForm,RegisterForm
import hashlib

from .models import Uers_profile
from ..blog.models import Collect
from apps.message_form.models import Message


def index(request):
    all_collect = Collect.objects.all()
    page = request.GET.get('page')
    if page:
        page = int(page)
    else:
        page = 1
    print('page param:', page)
    all_collect = Collect.objects.all()
    curr_collect = None
    top5_collect_list = Collect.objects.order_by('-publish_date')[:5]
    paginator = Paginator(all_collect, 6)
    page_num = paginator.num_pages
    print('page num:', page_num)
    page_collect_list = paginator.page(page)
    if page_collect_list.has_next():
        next_page = page + 1
    else:
        next_page = page
    if page_collect_list.has_previous():
        previous_page = page - 1

    else:
        previous_page = page

    return render(request, 'login/index.html',
                  {
                      'collect_list': page_collect_list,
                      'page_num': range(1, page_num + 1),
                      'curr_page': page,
                      'next_page': next_page,
                      'previous_page': previous_page,
                      'top5_collect_list': top5_collect_list,
                      'all_collect': all_collect,

                  }
                  )


#Detial页面
def get_detail_page(request, id):
    all_collect = Collect.objects.all()
    curr_collect = None
    previous_collect = None
    next_collect = None
    for index, collect in enumerate(all_collect):
        if index == 0:
            previous_index = 0
            next_index = index + 1
        elif index == len(all_collect) - 1:
            previous_index = index - 1
            next_index = index
        else:
            previous_index = index - 1
            next_index = index + 1
        if collect.id == id:
            curr_collect = collect
            previous_collect = all_collect[previous_index]
            next_collect = all_collect[next_index]
            break

    section_list = curr_collect.content.split("\n")
    return render(request, 'login/detail.html',
                  {
                      'all_collect': all_collect,
                      'curr_collect': curr_collect,
                      'section_list': section_list,
                      'previous_collect': previous_collect,
                      'next_collect': next_collect,
                      # 'local': local
                  }
                  )

#List页面
def get_list(request):
    page = request.GET.get('page')
    if page:
        page = int(page)
    else:
        page = 1
    print('page param:', page)
    all_collect = Collect.objects.all()
    top5_collect_list = Collect.objects.order_by('-publish_date')[:5]
    paginator = Paginator(all_collect, 6)
    page_num = paginator.num_pages
    print('page num:', page_num)
    page_collect_list = paginator.page(page)
    if page_collect_list.has_next():
        next_page = page + 1
    else:
        next_page = page
    if page_collect_list.has_previous():
        previous_page = page - 1

    else:
        previous_page = page

    return render(request, 'login/list.html',
                  {
                      'collect_list': page_collect_list,
                      'page_num': range(1, page_num + 1),
                      'curr_page': page,
                      'next_page': next_page,
                      'previous_page': previous_page,
                      'top5_collect_list': top5_collect_list,

                  }
                  )

def login(request):
    if request.session.get('is_login', None):
        return redirect("/index/")
    if request.method == "POST":
        login_form = UserForm(request.POST)
        message = "请检查填写的内容！"
        if login_form.is_valid():
            username = login_form.cleaned_data['username']
            password = login_form.cleaned_data['password']
            try:
                user = Uers_profile.objects.get(name=username)
                if user.password == hash_code(password):  # 哈希值和数据库内的值进行比对
                    request.session['is_login'] = True
                    request.session['user_id'] = user.id
                    request.session['user_name'] = user.name
                    return redirect('/index/')
                else:
                    message = "密码不正确！"
            except:
                message = "用户不存在！"
        return render(request, 'login/login.html', locals())

    login_form = UserForm()
    return render(request, 'login/login.html', locals())


def register(request):
    if request.session.get('is_login', None):
        # 登录状态不允许注册。你可以修改这条原则！
        return redirect("/index/")
    if request.method == "POST":
        register_form = RegisterForm(request.POST)
        message = "请检查填写的内容！"
        if register_form.is_valid():  # 获取数据
            username = register_form.cleaned_data['username']
            password1 = register_form.cleaned_data['password1']
            password2 = register_form.cleaned_data['password2']
            email = register_form.cleaned_data['email']
            sex = register_form.cleaned_data['sex']
            if password1 != password2:  # 判断两次密码是否相同
                message = "两次输入的密码不同！"
                return render(request, 'login/register.html', locals())
            else:
                same_name_user = Uers_profile.objects.filter(name=username)
                if same_name_user:  # 用户名唯一
                    message = '用户已经存在，请重新选择用户名！'
                    return render(request, 'login/register.html', locals())
                same_email_user = Uers_profile.objects.filter(email=email)
                if same_email_user:  # 邮箱地址唯一
                    message = '该邮箱地址已被注册，请使用别的邮箱！'
                    return render(request, 'login/register.html', locals())

                # 当一切都OK的情况下，创建新用户

                new_user = Uers_profile.objects.create()
                new_user.name = username
                new_user.password = hash_code(password1)  # 使用加密密码
                new_user.email = email
                new_user.sex = sex
                new_user.save()
                return redirect('/login/')  # 自动跳转到登录页面
    register_form = RegisterForm()
    return render(request, 'login/register.html', locals())

def logout(request):
    if not request.session.get('is_login',None):
        return redirect('/index/')
    request.session.flush()

    return redirect('/index/')

def hash_code(s, salt='mysite_login'):
    h = hashlib.sha256()
    s += salt
    h.update(s.encode())  # update方法只接收bytes类型
    return h.hexdigest()

def collect(request):
    # 从html中提取数据保存到数据库中
    # get 拉，POST 推
    message = Message()
    if request.method == "POST":
        name = request.POST.get("name", "")
        type = request.POST.get("type", "")
        value = request.POST.get("value", "")
        img_url = request.POST.get("img_url", "")
        province = request.POST.get("province", "")
        city = request.POST.get("city", "")
        lng = request.POST.get("lng", "")
        lat = request.POST.get("lat", "")
        location = request.POST.get("sever_add", "")
        content = request.POST.get("message", "")

        message.name = name
        message.type = type
        message.value = value
        message.img_url = img_url
        message.province = province
        message.city = city
        message.lng = lng
        message.lat = lat
        message.location = location
        message.content = content
        message.save()
        return render(request, "login/collect.html", {
            "message": message
        })


    if request.method == "GET":
        var_dict = {}
        all_message = Message.objects.all()
        if all_message:
            message = all_message[0]
            var_dict = {
                "message": message
            }
        return render(request, "login/collect.html",var_dict)